<template>
  <div class="problem-detail">
    <!-- 题目头部 -->
    <div class="problem-header">
      <div class="header-content">
        <div class="problem-info">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/coding' }">编程实战</el-breadcrumb-item>
              <el-breadcrumb-item :to="{ path: '/coding/problems' }">题目列表</el-breadcrumb-item>
              <el-breadcrumb-item>{{ problem.title }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="problem-main-info">
            <div class="problem-left">
              <div class="problem-number">第{{ problem.id }}题</div>
              <h1 class="problem-title">{{ problem.title }}</h1>

              <div class="problem-meta">
                <el-tag :type="getDifficultyType(problem.difficulty)" size="large">
                  {{ problem.difficulty }}
                </el-tag>
                <div class="problem-stats">
                  <span class="stat-item">
                    <el-icon><User /></el-icon>
                    {{ formatNumber(problem.submissions) }}人提交
                  </span>
                  <span class="stat-item">
                    <el-icon><CircleCheck /></el-icon>
                    {{ problem.acceptanceRate }}%通过率
                  </span>
                </div>
              </div>

              <div class="problem-tags">
                <el-tag
                  v-for="tag in problem.tags"
                  :key="tag"
                  size="small"
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <div class="problem-right">
              <div class="problem-actions">
                <el-button
                  type="primary"
                  size="large"
                  @click="startSolving"
                  :loading="starting"
                >
                  {{ getActionText() }}
                </el-button>

                <div class="action-buttons">
                  <el-button @click="toggleFavorite" :type="problem.isFavorited ? 'primary' : ''">
                    <el-icon><Star /></el-icon>
                    {{ problem.isFavorited ? '已收藏' : '收藏' }}
                  </el-button>
                  <el-button @click="shareProblem">
                    <el-icon><Share /></el-icon>
                    分享
                  </el-button>
                </div>
              </div>

              <div class="problem-status" v-if="problem.userStatus">
                <div class="status-card">
                  <div class="status-icon" :class="problem.userStatus">
                    <el-icon v-if="problem.userStatus === 'solved'"><CircleCheck /></el-icon>
                    <el-icon v-else><Warning /></el-icon>
                  </div>
                  <div class="status-text">
                    <div class="status-label">
                      {{ problem.userStatus === 'solved' ? '已解决' : '尝试过' }}
                    </div>
                    <div class="status-desc" v-if="problem.userBestSubmission">
                      最佳提交：{{ problem.userBestSubmission.runtime }}ms
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 题目内容 -->
    <div class="problem-content">
      <div class="content-container">
        <div class="main-content">
          <el-tabs v-model="activeTab" class="problem-tabs">
            <!-- 题目描述 -->
            <el-tab-pane label="题目描述" name="description">
              <div class="description-content">
                <section class="problem-statement">
                  <h3>题目描述</h3>
                  <div class="statement-text" v-html="problem.description"></div>
                </section>

                <section class="problem-examples" v-if="problem.examples">
                  <h3>示例</h3>
                  <div
                    v-for="(example, index) in problem.examples"
                    :key="index"
                    class="example-item"
                  >
                    <div class="example-header">示例 {{ index + 1 }}：</div>
                    <div class="example-content">
                      <div class="example-input">
                        <strong>输入：</strong>
                        <pre><code>{{ example.input }}</code></pre>
                      </div>
                      <div class="example-output">
                        <strong>输出：</strong>
                        <pre><code>{{ example.output }}</code></pre>
                      </div>
                      <div class="example-explanation" v-if="example.explanation">
                        <strong>解释：</strong>
                        <p>{{ example.explanation }}</p>
                      </div>
                    </div>
                  </div>
                </section>

                <section class="problem-constraints" v-if="problem.constraints">
                  <h3>提示</h3>
                  <ul class="constraints-list">
                    <li v-for="constraint in problem.constraints" :key="constraint">
                      {{ constraint }}
                    </li>
                  </ul>
                </section>
              </div>
            </el-tab-pane>

            <!-- 题解 -->
            <el-tab-pane label="题解" name="solution">
              <div class="solution-content">
                <div v-if="!problem.userStatus || problem.userStatus !== 'solved'" class="solution-locked">
                  <div class="lock-icon">
                    <el-icon><Lock /></el-icon>
                  </div>
                  <div class="lock-text">
                    <h3>题解已锁定</h3>
                    <p>请先解决此题目后查看官方题解</p>
                  </div>
                  <el-button type="primary" @click="startSolving">
                    开始解题
                  </el-button>
                </div>

                <div v-else class="solution-unlocked">
                  <div class="solution-approaches">
                    <div
                      v-for="(approach, index) in problem.solutions"
                      :key="index"
                      class="approach-item"
                    >
                      <h3>方法{{ index + 1 }}：{{ approach.title }}</h3>
                      <div class="approach-complexity">
                        <span class="complexity-item">
                          <strong>时间复杂度：</strong>{{ approach.timeComplexity }}
                        </span>
                        <span class="complexity-item">
                          <strong>空间复杂度：</strong>{{ approach.spaceComplexity }}
                        </span>
                      </div>
                      <div class="approach-description">
                        {{ approach.description }}
                      </div>
                      <div class="approach-code">
                        <pre><code>{{ approach.code }}</code></pre>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 提交记录 -->
            <el-tab-pane label="提交记录" name="submissions">
              <div class="submissions-content">
                <div v-if="userSubmissions.length === 0" class="no-submissions">
                  <EmptyState
                    image="/images/empty-submissions.svg"
                    title="暂无提交记录"
                    description="您还没有提交过这道题目"
                  />
                </div>

                <div v-else class="submissions-list">
                  <div
                    v-for="submission in userSubmissions"
                    :key="submission.id"
                    class="submission-item"
                  >
                    <div class="submission-header">
                      <div class="submission-info">
                        <div class="submission-time">{{ formatDateTime(submission.submittedAt) }}</div>
                        <div class="submission-language">{{ submission.language }}</div>
                      </div>
                      <div class="submission-result">
                        <div class="status" :class="getStatusClass(submission.status)">
                          {{ getStatusText(submission.status) }}
                        </div>
                        <div class="metrics" v-if="submission.runtime">
                          <span>{{ submission.runtime }}ms</span>
                          <span>{{ submission.memory }}MB</span>
                        </div>
                      </div>
                    </div>

                    <div class="submission-actions">
                      <el-button size="small" @click="viewSubmissionCode(submission)">
                        查看代码
                      </el-button>
                      <el-button size="small" type="primary" @click="resubmitCode(submission)">
                        重新提交
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 侧边栏 -->
        <div class="sidebar">
          <!-- 相似题目 -->
          <div class="similar-problems">
            <h3>相似题目</h3>
            <div class="similar-list">
              <div
                v-for="similarProblem in similarProblems"
                :key="similarProblem.id"
                class="similar-item"
                @click="viewProblem(similarProblem)"
              >
                <div class="similar-info">
                  <div class="similar-title">{{ similarProblem.title }}</div>
                  <div class="similar-meta">
                    <el-tag :type="getDifficultyType(similarProblem.difficulty)" size="small">
                      {{ similarProblem.difficulty }}
                    </el-tag>
                    <span class="similar-acceptance">{{ similarProblem.acceptanceRate }}%</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 题目统计 -->
          <div class="problem-statistics">
            <h3>题目统计</h3>
            <div class="stats-list">
              <div class="stat-item">
                <div class="stat-label">总提交数</div>
                <div class="stat-value">{{ formatNumber(problem.submissions) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">通过数</div>
                <div class="stat-value">{{ formatNumber(Math.floor(problem.submissions * problem.acceptanceRate / 100)) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">通过率</div>
                <div class="stat-value">{{ problem.acceptanceRate }}%</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">难度</div>
                <div class="stat-value">{{ problem.difficulty }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  User, CircleCheck, Star, Share, Warning, Lock
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 响应式数据
const activeTab = ref('description')
const starting = ref(false)

// 模拟题目数据
const problem = ref({
  id: 1,
  title: '两数之和',
  difficulty: '简单',
  tags: ['数组', '哈希表'],
  submissions: 1250000,
  acceptanceRate: 49.2,
  isFavorited: false,
  userStatus: 'solved', // 'solved', 'attempted', null
  userBestSubmission: {
    runtime: 68,
    memory: 15.2
  },
  description: `
    <p>给定一个整数数组 <code>nums</code> 和一个整数目标值 <code>target</code>，请你在该数组中找出 <strong>和为目标值</strong> <em>target</em> 的那 <strong>两个</strong> 整数，并返回它们的数组下标。</p>
    <p>你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。</p>
    <p>你可以按任意顺序返回答案。</p>
  `,
  examples: [
    {
      input: 'nums = [2,7,11,15], target = 9',
      output: '[0,1]',
      explanation: '因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。'
    },
    {
      input: 'nums = [3,2,4], target = 6',
      output: '[1,2]',
      explanation: '因为 nums[1] + nums[2] == 6 ，返回 [1, 2] 。'
    },
    {
      input: 'nums = [3,3], target = 6',
      output: '[0,1]',
      explanation: '因为 nums[0] + nums[1] == 6 ，返回 [0, 1] 。'
    }
  ],
  constraints: [
    '2 <= nums.length <= 10^4',
    '-10^9 <= nums[i] <= 10^9',
    '-10^9 <= target <= 10^9',
    '只会存在一个有效答案'
  ],
  solutions: [
    {
      title: '暴力枚举',
      timeComplexity: 'O(n²)',
      spaceComplexity: 'O(1)',
      description: '使用两层循环遍历数组，检查每一对数字的和是否等于目标值。',
      code: `function twoSum(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                return [i, j];
            }
        }
    }
    return [];
}`
    },
    {
      title: '哈希表',
      timeComplexity: 'O(n)',
      spaceComplexity: 'O(n)',
      description: '使用哈希表存储已遍历的数字及其索引，对于每个数字，检查目标值减去当前数字的差值是否在哈希表中。',
      code: `function twoSum(nums, target) {
    const map = new Map();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (map.has(complement)) {
            return [map.get(complement), i];
        }
        map.set(nums[i], i);
    }
    return [];
}`
    }
  ]
})

const userSubmissions = ref([
  {
    id: 1,
    status: 'accepted',
    runtime: 68,
    memory: 15.2,
    language: 'JavaScript',
    submittedAt: new Date('2024-01-15 14:30:00')
  },
  {
    id: 2,
    status: 'wrong_answer',
    runtime: null,
    memory: null,
    language: 'JavaScript',
    submittedAt: new Date('2024-01-15 14:25:00')
  },
  {
    id: 3,
    status: 'time_limit_exceeded',
    runtime: null,
    memory: null,
    language: 'JavaScript',
    submittedAt: new Date('2024-01-15 14:20:00')
  }
])

const similarProblems = ref([
  {
    id: 15,
    title: '三数之和',
    difficulty: '中等',
    acceptanceRate: 32.1
  },
  {
    id: 18,
    title: '四数之和',
    difficulty: '中等',
    acceptanceRate: 35.8
  },
  {
    id: 167,
    title: '两数之和 II - 输入有序数组',
    difficulty: '简单',
    acceptanceRate: 58.7
  }
])

// 计算属性
const getActionText = () => {
  if (problem.value.userStatus === 'solved') return '重新解题'
  if (problem.value.userStatus === 'attempted') return '继续解题'
  return '开始解题'
}

// 方法
const getDifficultyType = (difficulty) => {
  const types = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return types[difficulty] || 'info'
}

const getStatusClass = (status) => {
  const classes = {
    'accepted': 'success',
    'wrong_answer': 'error',
    'time_limit_exceeded': 'warning',
    'runtime_error': 'error',
    'compile_error': 'error'
  }
  return classes[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    'accepted': '通过',
    'wrong_answer': '答案错误',
    'time_limit_exceeded': '超时',
    'runtime_error': '运行错误',
    'compile_error': '编译错误'
  }
  return texts[status] || '未知'
}

const formatNumber = (num) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const startSolving = async () => {
  starting.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    router.push(`/coding/editor/${problem.value.id}`)
  } catch (error) {
    ElMessage.error('进入编辑器失败，请重试')
  } finally {
    starting.value = false
  }
}

const toggleFavorite = () => {
  problem.value.isFavorited = !problem.value.isFavorited
  ElMessage.success(problem.value.isFavorited ? '已收藏' : '已取消收藏')
}

const shareProblem = () => {
  ElMessage.success('分享链接已复制到剪贴板')
}

const viewSubmissionCode = (submission) => {
  ElMessage.info(`查看提交代码：${submission.id}`)
}

const resubmitCode = (submission) => {
  router.push(`/coding/editor/${problem.value.id}`)
}

const viewProblem = (similarProblem) => {
  router.push(`/coding/problem/${similarProblem.id}`)
}

onMounted(() => {
  // 根据路由参数加载题目数据
  const problemId = route.params.id
  if (problemId) {
    // 加载题目详情数据
  }
})
</script>

<style lang="scss" scoped>
.problem-detail {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.problem-header {
  background: white;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  padding: 20px 0 40px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.problem-main-info {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 40px;

  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
    gap: 30px;
  }
}

.problem-number {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.problem-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--el-text-color-primary);
  margin-bottom: 16px;
  line-height: 1.2;

  @media (max-width: 768px) {
    font-size: 24px;
  }
}

.problem-meta {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.problem-stats {
  display: flex;
  gap: 16px;

  .stat-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: var(--el-text-color-secondary);

    .el-icon {
      color: var(--el-color-primary);
    }
  }
}

.problem-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.problem-actions {
  margin-bottom: 20px;

  .el-button {
    width: 100%;
    margin-bottom: 12px;
  }

  .action-buttons {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;

    .el-button {
      margin-bottom: 0;
    }
  }
}

.problem-status {
  .status-card {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px;
    background: var(--el-fill-color-extra-light);
    border-radius: 8px;

    .status-icon {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      &.solved {
        background: var(--el-color-success-light-9);
        color: var(--el-color-success);
      }

      &.attempted {
        background: var(--el-color-warning-light-9);
        color: var(--el-color-warning);
      }
    }

    .status-text {
      .status-label {
        font-weight: 500;
        margin-bottom: 2px;
        color: var(--el-text-color-primary);
      }

      .status-desc {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

.problem-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.content-container {
  display: grid;
  grid-template-columns: 1fr 280px;
  gap: 40px;

  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
}

.problem-tabs {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.description-content {
  section {
    margin-bottom: 32px;

    h3 {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 16px;
      color: var(--el-text-color-primary);
    }
  }
}

.statement-text {
  line-height: 1.6;
  color: var(--el-text-color-regular);

  :deep(code) {
    background: var(--el-fill-color-extra-light);
    padding: 2px 4px;
    border-radius: 3px;
    font-family: 'Consolas', 'Monaco', monospace;
  }
}

.example-item {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;

  .example-header {
    background: var(--el-fill-color-extra-light);
    padding: 8px 16px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .example-content {
    padding: 16px;

    .example-input,
    .example-output {
      margin-bottom: 12px;

      strong {
        color: var(--el-text-color-primary);
      }

      pre {
        background: var(--el-fill-color-extra-light);
        padding: 8px 12px;
        border-radius: 4px;
        margin: 4px 0;
        font-family: 'Consolas', 'Monaco', monospace;
        font-size: 14px;
        overflow-x: auto;
      }
    }

    .example-explanation {
      p {
        margin: 4px 0 0;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

.constraints-list {
  list-style: disc;
  padding-left: 20px;

  li {
    margin-bottom: 8px;
    color: var(--el-text-color-regular);
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 14px;
  }
}

.solution-content {
  .solution-locked {
    text-align: center;
    padding: 60px 20px;

    .lock-icon {
      font-size: 48px;
      color: var(--el-text-color-placeholder);
      margin-bottom: 16px;
    }

    .lock-text {
      margin-bottom: 24px;

      h3 {
        font-size: 18px;
        margin-bottom: 8px;
        color: var(--el-text-color-primary);
      }

      p {
        color: var(--el-text-color-secondary);
      }
    }
  }

  .solution-unlocked {
    .approach-item {
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;

      h3 {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 12px;
        color: var(--el-text-color-primary);
      }

      .approach-complexity {
        display: flex;
        gap: 20px;
        margin-bottom: 12px;

        .complexity-item {
          font-size: 14px;
          color: var(--el-text-color-secondary);

          strong {
            color: var(--el-text-color-primary);
          }
        }
      }

      .approach-description {
        margin-bottom: 16px;
        line-height: 1.6;
        color: var(--el-text-color-regular);
      }

      .approach-code {
        background: var(--el-fill-color-extra-light);
        border-radius: 6px;
        padding: 16px;

        pre {
          margin: 0;
          font-family: 'Consolas', 'Monaco', monospace;
          font-size: 14px;
          line-height: 1.4;
          overflow-x: auto;
        }
      }
    }
  }
}

.submissions-content {
  .no-submissions {
    text-align: center;
    padding: 40px 20px;
  }

  .submissions-list {
    .submission-item {
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 12px;

      .submission-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .submission-info {
          .submission-time {
            font-size: 14px;
            margin-bottom: 4px;
            color: var(--el-text-color-primary);
          }

          .submission-language {
            font-size: 12px;
            color: var(--el-text-color-placeholder);
          }
        }

        .submission-result {
          text-align: right;

          .status {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;

            &.success {
              color: var(--el-color-success);
            }

            &.error {
              color: var(--el-color-danger);
            }

            &.warning {
              color: var(--el-color-warning);
            }
          }

          .metrics {
            font-size: 12px;
            color: var(--el-text-color-placeholder);

            span {
              margin-left: 8px;
            }
          }
        }
      }

      .submission-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
}

.sidebar {
  .similar-problems,
  .problem-statistics {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    margin-bottom: 20px;

    h3 {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 16px;
      color: var(--el-text-color-primary);
    }
  }
}

.similar-list {
  .similar-item {
    padding: 12px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 6px;
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary);
      background: var(--el-fill-color-extra-light);
    }

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.similar-info {
  .similar-title {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 8px;
    color: var(--el-text-color-primary);
    @include text-ellipsis(2);
  }

  .similar-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .similar-acceptance {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
}

.stats-list {
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid var(--el-border-color-extra-light);

    &:last-child {
      border-bottom: none;
    }

    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }

    .stat-value {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
}

@media (max-width: 768px) {
  .problem-main-info {
    grid-template-columns: 1fr;
  }

  .content-container {
    grid-template-columns: 1fr;
  }

  .submission-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .submission-result {
    text-align: left !important;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .approach-complexity {
    flex-direction: column !important;
    gap: 8px !important;
  }
}
</style>